package xyz.scootaloo.oj.leetcode

import org.junit.Test

/**
 * 未通过
 * @author flutterdash@qq.com
 * @since 2021/4/6 22:49
 */
class P80 {

    /** 0  1  2  3  4  5  6
     * [1, 1, 1, 1, 2, 2, 3]  size: 6
     *        ^
     */
    private fun removeDuplicates(nums: IntArray): Int {
        if (nums.size <= 2)
            return nums.size
        var validSize = 1
        var repeatCount = 1
        var pos = 1
        val size = nums.size
        while (pos < size) {
            val previous = nums[validSize - 1]
            if (nums[pos] == previous) {
                if (repeatCount == 2) {
                    while (pos < size && nums[pos] == previous)
                        pos++
                    if (pos == size)
                        return validSize
                    nums[validSize] = nums[pos]
                    repeatCount = 1
                } else {
                    shift(nums, pos, validSize)
                    repeatCount++
                }
            } else {
                shift(nums, pos, validSize)
                repeatCount = 1
            }
            validSize++
            pos++
        }
        return validSize
    }

    private fun shift(arr: IntArray, pos: Int, target: Int) {
        if (pos == target)
            return
        arr[target] = arr[pos]
    }

    @Test
    fun test0() {
        val arr = intArrayOf(1, 1, 1, 1, 2, 2, 3, 3, 2)
        println(removeDuplicates(arr))
        println(arr.contentToString())
    }

}
